<template>
	<div class="system-user-dialog-container">
		<el-dialog :title="state.dialog.title" v-model="state.dialog.isShowDialog" width="769px">
			<el-form 
			:rules="state.rules"
			ref="userDialogFormRef" 
			:model="state.ruleForm" 
			size="default" 
			status-icon
			label-width="100px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="分组名称" prop="name">
							<el-input type="name" v-model="state.ruleForm.name" placeholder="请输入分组名称" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="轮播图位置" prop="position">
							<el-select v-model="state.ruleForm.position" placeholder="请选择轮播图位置">
								<el-option v-for="item in state.classData" :key="item.id" :label="item.name" :value="item.id"></el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="图片"  prop="path">
							<el-upload
								v-model:file-list="state.ruleForm.banner"
								list-type="picture-card"
								:action="state.action"
								:on-preview="handlePictureCardPreview"
								:on-remove="handleRemove"
								>
								<el-icon><Plus /></el-icon>
							</el-upload>
							
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" v-if="state.ruleForm.banner.length > 0">
						<el-form-item :label="'图片'+(index+1)" v-for="(item, index) in state.ruleForm.banner" :key="index">
							<el-input v-model="item.to" placeholder="请输入跳转地址，如果不跳转则不填写，留空即可" clearable></el-input>
						</el-form-item>
					
					</el-col>		
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
			</template>
		</el-dialog>
		<el-dialog v-model="dialogVisible">
			<img w-full :src="dialogImageUrl" alt="Preview Image" />
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemUserDialog">
import { reactive, ref } from 'vue';
import { ElMessage } from 'element-plus';
import { useBannerApi } from '/@/api/banner/';
import { Plus } from '@element-plus/icons-vue';
import type { UploadProps } from 'element-plus'

const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
	//删除
  console.log(uploadFile, uploadFiles)
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const state = reactive({
	ruleForm: {
		name: '', // 账户名称
		banner: ref<any[]>([]),
		position:'',
	},
	rules: {
		name: { required: true, message: '请输入分组名称', trigger: 'blur' },
		position: { required: true, message: '请输入轮播图位置', trigger: 'blur' },
	},
	dialog: {
		isShowDialog: false,
		type: '',
		title: '',
		submitTxt: '',
	},
	roleOptions: [] as RoleOptionType[],
	type: 'add',
	classData:[] as ClassType[],
	action: import.meta.env.VITE_API_URL+'/common/upload',
});
// 打开弹窗
const openDialog = (type: string, row: any) => {
	state.type = type;
	if (type === 'edit') {
		getMenuData().then(() => {
			// 将选中的分类转换为数组
			state.ruleForm = { ...row }; // 复制行数据到表单
		});
		state.dialog.title = '修改';
		state.dialog.submitTxt = '修 改';
	} else {
		getMenuData()
		Object.assign(state.ruleForm, {
			name:'',
			banner: [],
			position: '',
		});
		state.dialog.title = '新增';
		state.dialog.submitTxt = '新 增';
	}
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};
// 取消
const onCancel = () => {
	closeDialog();
};
const formRulesValidate = (pageRef: RefType) => {
	return new Promise((resolve) => {
		pageRef.value.validate((valid: boolean) => {
			if (valid) resolve(valid);
		});
	});
};
// 提交
const onSubmit = () => {
	Promise.all([
		formRulesValidate(userDialogFormRef),
	]).then(async() => {
		//请求后端添加数据
		if(state.type==='edit'){
			// await useMaterialApi().postUserEdit(state.ruleForm);
		}else{
			await useBannerApi().postAdd(state.ruleForm);
		}
		closeDialog();
		emit('refresh');
		ElMessage.success('操作成功');
	});
	// if (state.dialog.type === 'add') { }
};
//初始化角色数据
// 获取 pinia 中的路由
const getMenuData = async() => {
	try{
		const response = await useBannerApi().getPositions();
		state.classData = response.data;
	}catch(error){
		// console.error('获取数据失败:', error);
	}
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
